import router, { findFirstValidRoute } from './router'
import { useUserStore } from '@/stores/user'
import { useTabsStore } from '@/stores/multipleTabs'
import { PageEnum } from '@/enums/pageEnum'
import { INDEX_ROUTE, INDEX_ROUTE_NAME } from './router/routes'
import { clearAuthInfo } from '@/utils/auth'
import { isExternal } from '@/utils/validate'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const loginPath = PageEnum.LOGIN
const defaultPath = PageEnum.INDEX
// 免登录白名单
const whiteList = [PageEnum.LOGIN, PageEnum.ERROR_403]

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => { 
    document.title = to.meta.title ?? '后台管理系统'
  const userStore = useUserStore() 
  const tabsStore = useTabsStore()
 
  if (whiteList.includes(to.path)) {
      // 在免登录白名单，直接进入
      next()
  } else if (userStore.token) {
      // 获取用户信息
      const hasGetUserInfo = Object.keys(userStore.userInfo).length !== 0
      if (hasGetUserInfo) {
          if (to.path === loginPath) {
              next({ path: defaultPath })
          } else {
              next()
          }
      } else {
          try {
              await userStore.getUserInfo()
              const routes = userStore.routes
              // 找到第一个有效路由
              const routeName = findFirstValidRoute(routes)
              // 没有有效路由跳转到403页面
              if (!routeName) {
                  clearAuthInfo()
                  next(PageEnum.ERROR_403)
                  return
              } 
              tabsStore.setRouteName(routeName)
              INDEX_ROUTE.redirect = { name: routeName }

              // 动态添加index路由
              router.addRoute(INDEX_ROUTE)
              routes.forEach((route) => {
                  // https 则不插入
                  if (isExternal(route.path)) {
                      return
                  }
                  if (!route.children) {
                      router.addRoute(INDEX_ROUTE_NAME, route)
                      return
                  }
                  // 动态添加可访问路由表
                  router.addRoute(route)
              }) 
              next(to.fullPath)
          } catch (err) {
              console.log("🚀 ~ router.beforeEach ~ err:", err)
              clearAuthInfo()
              next({ path: loginPath, query: { redirect: to.fullPath } })
          }
      }
  } else {
      next({ path: loginPath, query: { redirect: to.fullPath } })
  }
})
 